//! 交易API
//! 
//! 提供统一的交易接口，支持所有产品线

use crate::errors::Result;
use crate::rest::RestClient;
use crate::models::*;
use std::collections::HashMap;

/// 交易API
pub struct TradeApi<'a> {
    client: &'a RestClient,
}

impl<'a> TradeApi<'a> {
    pub fn new(client: &'a RestClient) -> Self {
        Self { client }
    }

    /// 下单
    pub async fn place_order(&self, order: &OrderRequest) -> Result<OrderResponse> {
        let mut params = HashMap::new();
        
        params.insert("symbol".to_string(), order.symbol.clone());
        params.insert("side".to_string(), order.side.to_string());
        params.insert("type".to_string(), order.order_type.to_string());
        
        if let Some(quantity) = &order.quantity {
            params.insert("quantity".to_string(), quantity.to_string());
        }
        if let Some(price) = &order.price {
            params.insert("price".to_string(), price.to_string());
        }
        if let Some(time_in_force) = &order.time_in_force {
            params.insert("timeInForce".to_string(), time_in_force.to_string());
        }
        if let Some(client_order_id) = &order.new_client_order_id {
            params.insert("newClientOrderId".to_string(), client_order_id.clone());
        }
        if let Some(stop_price) = &order.stop_price {
            params.insert("stopPrice".to_string(), stop_price.to_string());
        }
        if let Some(iceberg_qty) = &order.iceberg_qty {
            params.insert("icebergQty".to_string(), iceberg_qty.to_string());
        }
        if let Some(new_order_resp_type) = &order.new_order_resp_type {
            params.insert("newOrderRespType".to_string(), new_order_resp_type.to_string());
        }
        if let Some(recv_window) = order.recv_window {
            params.insert("recvWindow".to_string(), recv_window.to_string());
        }

        let response = self.client.post("/order", &params, true).await?;
        let order_response: OrderResponse = serde_json::from_str(&response)?;
        Ok(order_response)
    }

    /// 批量下单
    pub async fn place_batch_orders(&self, orders: &[OrderRequest]) -> Result<Vec<OrderResponse>> {
        let mut params = HashMap::new();
        
        let batch_orders: Vec<serde_json::Value> = orders.iter()
            .map(|order| {
                let mut order_json = serde_json::Map::new();
                order_json.insert("symbol".to_string(), serde_json::Value::String(order.symbol.clone()));
                order_json.insert("side".to_string(), serde_json::Value::String(order.side.to_string()));
                order_json.insert("type".to_string(), serde_json::Value::String(order.order_type.to_string()));
                
                if let Some(quantity) = &order.quantity {
                    order_json.insert("quantity".to_string(), serde_json::Value::String(quantity.to_string()));
                }
                if let Some(price) = &order.price {
                    order_json.insert("price".to_string(), serde_json::Value::String(price.to_string()));
                }
                if let Some(time_in_force) = &order.time_in_force {
                    order_json.insert("timeInForce".to_string(), serde_json::Value::String(time_in_force.to_string()));
                }
                if let Some(client_order_id) = &order.new_client_order_id {
                    order_json.insert("newClientOrderId".to_string(), serde_json::Value::String(client_order_id.clone()));
                }
                
                serde_json::Value::Object(order_json)
            })
            .collect();
        
        params.insert("batchOrders".to_string(), serde_json::to_string(&batch_orders)?);

        let response = self.client.post("/batchOrders", &params, true).await?;
        let batch_response: Vec<OrderResponse> = serde_json::from_str(&response)?;
        Ok(batch_response)
    }

    /// 查询订单
    pub async fn get_order(&self, symbol: &str, order_id: Option<u64>, orig_client_order_id: Option<&str>) -> Result<OrderInfo> {
        let mut endpoint = format!("/order?symbol={}", symbol);
        
        if let Some(id) = order_id {
            endpoint.push_str(&format!("&orderId={}", id));
        }
        if let Some(client_id) = orig_client_order_id {
            endpoint.push_str(&format!("&origClientOrderId={}", client_id));
        }
        
        let response = self.client.get(&endpoint, true).await?;
        let order_info: OrderInfo = serde_json::from_str(&response)?;
        Ok(order_info)
    }

    /// 查询所有订单
    pub async fn get_all_orders(
        &self,
        symbol: &str,
        order_id: Option<u64>,
        start_time: Option<u64>,
        end_time: Option<u64>,
        limit: Option<u32>,
    ) -> Result<Vec<OrderInfo>> {
        let mut endpoint = format!("/allOrders?symbol={}", symbol);
        
        if let Some(id) = order_id {
            endpoint.push_str(&format!("&orderId={}", id));
        }
        if let Some(start) = start_time {
            endpoint.push_str(&format!("&startTime={}", start));
        }
        if let Some(end) = end_time {
            endpoint.push_str(&format!("&endTime={}", end));
        }
        if let Some(l) = limit {
            endpoint.push_str(&format!("&limit={}", l));
        }
        
        let response = self.client.get(&endpoint, true).await?;
        let orders: Vec<OrderInfo> = serde_json::from_str(&response)?;
        Ok(orders)
    }

    /// 查询开放订单
    pub async fn get_open_orders(&self, symbol: Option<&str>) -> Result<Vec<OrderInfo>> {
        let endpoint = if let Some(sym) = symbol {
            format!("/openOrders?symbol={}", sym)
        } else {
            "/openOrders".to_string()
        };
        
        let response = self.client.get(&endpoint, true).await?;
        let orders: Vec<OrderInfo> = serde_json::from_str(&response)?;
        Ok(orders)
    }

    /// 撤销订单
    pub async fn cancel_order(&self, symbol: &str, order_id: Option<u64>, orig_client_order_id: Option<&str>) -> Result<CancelOrderResponse> {
        let mut endpoint = format!("/order?symbol={}", symbol);
        
        if let Some(id) = order_id {
            endpoint.push_str(&format!("&orderId={}", id));
        }
        if let Some(client_id) = orig_client_order_id {
            endpoint.push_str(&format!("&origClientOrderId={}", client_id));
        }
        
        let response = self.client.delete(&endpoint, true).await?;
        let cancel_response: CancelOrderResponse = serde_json::from_str(&response)?;
        Ok(cancel_response)
    }

    /// 撤销所有订单
    pub async fn cancel_all_orders(&self, symbol: Option<&str>) -> Result<Vec<CancelOrderResponse>> {
        let endpoint = if let Some(sym) = symbol {
            format!("/openOrders?symbol={}", sym)
        } else {
            "/openOrders".to_string()
        };
        
        let response = self.client.delete(&endpoint, true).await?;
        let cancel_responses: Vec<CancelOrderResponse> = serde_json::from_str(&response)?;
        Ok(cancel_responses)
    }

    /// 查询账户交易历史
    pub async fn get_account_trades(
        &self,
        symbol: &str,
        from_id: Option<u64>,
        order_id: Option<u64>,
        start_time: Option<u64>,
        end_time: Option<u64>,
        limit: Option<u32>,
    ) -> Result<Vec<AccountTrade>> {
        let mut endpoint = format!("/myTrades?symbol={}", symbol);
        
        if let Some(id) = from_id {
            endpoint.push_str(&format!("&fromId={}", id));
        }
        if let Some(id) = order_id {
            endpoint.push_str(&format!("&orderId={}", id));
        }
        if let Some(start) = start_time {
            endpoint.push_str(&format!("&startTime={}", start));
        }
        if let Some(end) = end_time {
            endpoint.push_str(&format!("&endTime={}", end));
        }
        if let Some(l) = limit {
            endpoint.push_str(&format!("&limit={}", l));
        }
        
        let response = self.client.get(&endpoint, true).await?;
        let trades: Vec<AccountTrade> = serde_json::from_str(&response)?;
        Ok(trades)
    }
}
